package thread;

import java.util.concurrent.Semaphore;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-09-30
 * Time: 10:33
 */
public class ThreadDemon40 {
    private static int count = 0;
    //引入Semaphore进行加锁
    private static Semaphore semaphore = new Semaphore(1);
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                semaphore.acquire();//加锁
                for (int i = 1 ; i <= 50000 ; i++){
                    count++;
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            semaphore.release();//解锁
        });
        Thread t2 = new Thread(() ->{
            try {
                semaphore.acquire();//加锁
                for (int i = 1 ; i <= 50000 ; i++){
                    count++;
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            semaphore.release();//解锁
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(count);
    }
}
